/*
 * FileDialog.java
 *
 * Created on 16 July 2006, 12:17
 */

package andyr.jtokeniser.gui;

import java.io.File;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
import java.util.Vector;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

/**
 *
 * @author  Andy Roberts
 */
public class FileDialog extends javax.swing.JDialog {
    
    private JFileChooser fc;
     
    public static final int OPEN = 3;
    public static final int SAVE = 4;
    
    final static int OK = 0;
    final static int CANCEL = 1;
    final static int ERROR = 2;

    private int returnVal = ERROR; 
    
    protected int type = OPEN; // Open by default
    protected Map<String,String> encodings;
    protected Vector<String> encodingsVector;
    protected String defaultEncoding;
    
    /** Creates new form FileDialog */
    public FileDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        this.encodings = new HashMap<String,String>();
        initComponents();
    }
    
    public FileDialog(java.awt.Frame parent, boolean modal, int type, Map<String,String> encodings) {
        super(parent, modal);
        this.type = type;
        this.encodings = encodings;
        encodingsVector = new Vector(encodings.values());
        this.defaultEncoding = defaultEncoding;
        Collections.sort(encodingsVector);
        
        if (type == FileDialog.OPEN) {
            this.setTitle("Open file");
        }
        else if (type == FileDialog.SAVE) {
            this.setTitle("Save file");
        }
        
        initComponents();
        
        txtFilename.getDocument().addDocumentListener(new DocumentListener() {
            public void insertUpdate(DocumentEvent e) {
                updateButtons();
            }

            public void removeUpdate(DocumentEvent e) {
                updateButtons();
            }

            public void changedUpdate(DocumentEvent e) {
                updateButtons();
            }
            
        });
        setupFileChooserDialog();
        pack();
        setLocationRelativeTo(parent);
    }
    
    private void setupFileChooserDialog() {
        
        if (this.type == OPEN) {
        fc = new JFileChooser() {
            
            public void approveSelection() {
                File f = getSelectedFile();
                if (f.exists()) {
                    super.approveSelection();
                } else {
                    JOptionPane.showMessageDialog(this, f + ": does not exist", "File Open Error", JOptionPane.ERROR_MESSAGE);
                }
            }
        };
        }
        else {
            fc = new JFileChooser();
        }
    }
    
    private String getDefaultEncoding() {
        
        String defaultEnc = "";
        
        if (encodings.containsKey(java.nio.charset.Charset.defaultCharset().name())) {
            defaultEnc = encodings.get(java.nio.charset.Charset.defaultCharset().name());
        }
        
        return defaultEnc;
     
    }
    
    public int showDialog() {
        setVisible(true);
        return returnVal;
    }
    
    protected void updateButtons() {
        if (txtFilename.getText().trim().equals("")) {
            btnOk.setEnabled(false);
        }
        else {
            btnOk.setEnabled(true);
        }
    }
 
    public String getFilename() {
        return txtFilename.getText();
    }
    
    public String getSelectedEncoding() {
        String displayEncoding = (String)cboEncodings.getSelectedItem();
        return displayEncoding.substring(0, displayEncoding.indexOf(" "));
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        lblFilename = new javax.swing.JLabel();
        lblEncodings = new javax.swing.JLabel();
        cboEncodings = new javax.swing.JComboBox();
        btnBrowse = new javax.swing.JButton();
        txtFilename = new javax.swing.JTextField();
        btnCancel = new javax.swing.JButton();
        btnOk = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        lblFilename.setText("Filename");

        lblEncodings.setText("Encodings");

        cboEncodings.setModel(new DefaultComboBoxModel(encodingsVector));
        cboEncodings.setSelectedItem(getDefaultEncoding());

        btnBrowse.setText("Browse");
        btnBrowse.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBrowseActionPerformed(evt);
            }
        });

        txtFilename.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                txtFilenamePropertyChange(evt);
            }
        });

        btnCancel.setText("Cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        btnOk.setText("Ok");
        btnOk.setEnabled(false);
        if (type== FileDialog.OPEN) { btnOk.setText("Open"); }
        else if (type == FileDialog.SAVE) {btnOk.setText("Save");}
        btnOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOkActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(lblEncodings)
                            .add(lblFilename))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(layout.createSequentialGroup()
                                .add(txtFilename, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 253, Short.MAX_VALUE)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(btnBrowse))
                            .add(cboEncodings, 0, 326, Short.MAX_VALUE)))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(btnOk)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(btnCancel)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(lblFilename)
                    .add(btnBrowse)
                    .add(txtFilename, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(lblEncodings)
                    .add(cboEncodings, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 63, Short.MAX_VALUE)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(btnCancel)
                    .add(btnOk))
                .addContainerGap())
        );
        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtFilenamePropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_txtFilenamePropertyChange
        updateButtons();
    }//GEN-LAST:event_txtFilenamePropertyChange

    private void btnBrowseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBrowseActionPerformed
        int returnVal = fc.showOpenDialog(this);

	if (returnVal == JFileChooser.APPROVE_OPTION) {
            String oldText = txtFilename.getText();
            txtFilename.setText(fc.getSelectedFile().getAbsolutePath());
            //txtFilename.firePropertyChange("text", oldText, txtFilename.getText());
            
            
            
        }
                
    }//GEN-LAST:event_btnBrowseActionPerformed

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        returnVal = CANCEL;
        dispose();
    }//GEN-LAST:event_btnCancelActionPerformed

    private void btnOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOkActionPerformed
        returnVal = OK;
        dispose(); 
    }//GEN-LAST:event_btnOkActionPerformed

    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBrowse;
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnOk;
    private javax.swing.JComboBox cboEncodings;
    private javax.swing.JLabel lblEncodings;
    private javax.swing.JLabel lblFilename;
    private javax.swing.JTextField txtFilename;
    // End of variables declaration//GEN-END:variables
    
}
